package com.blue.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.blue.common.utils.ThreadLocalUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author nanjie.chen
 * Created on 2022/3/25
 */
@Component
public class DataAutoFillHandler implements MetaObjectHandler {

    private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime", format.format(new Date()), metaObject);
        this.setFieldValByName("isFlag", "0", metaObject);
        if (ThreadLocalUtils.getLoginUserInfo() != null) {
            this.setFieldValByName("creatorId", ThreadLocalUtils.getLoginUserInfo().getUserId(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", format.format(new Date()), metaObject);
        if (ThreadLocalUtils.getLoginUserInfo() != null) {
            this.setFieldValByName("updaterId", ThreadLocalUtils.getLoginUserInfo().getUserId(), metaObject);
        }
    }
}
